package com.mycode.chapter02.server;

// import com.mycode.chapter02.server.Request;
// import com.mycode.chapter02.server.Response;
import com.mycode.chapter02.processor.Processor;
import com.mycode.chapter02.processor.ServletProcessor;
import com.mycode.chapter02.processor.ServletProcessor2;
import com.mycode.chapter02.processor.StaticResourceProcessor;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class HttpServer {

    // shutdown command
    private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

    // the shutdown command received
    private boolean shutdown = false;

    public static void main(String[] args) {
        HttpServer httpServer = new HttpServer();
        httpServer.await();
    }

    private void await() {
        int port = 8080;
        ServerSocket serverSocket = null;
        try {
            // serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
            serverSocket = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        while (!shutdown) {
            Socket socket = null;
            InputStream inputStream = null;
            OutputStream outputStream = null;
            try {
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                outputStream = socket.getOutputStream();

                Request request = new Request(inputStream);
                request.parse();

                Response response = new Response(outputStream);
                response.setRequest(request);
                // response.sendStaticResource();

                Processor processor = null;
                // 判断是否为 请求 servlet 资源
                if (request.getUri().startsWith("/servlet/")) {
                    // 处理器
                    processor = new ServletProcessor2();
                }
                else {
                    // 处理静态资源
                    processor = new StaticResourceProcessor();
                }
                // 处理
                processor.process(request, response);

                socket.close();
                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }

}
